using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay.City
{
    public class GameObjectPool
    {
        // ab包路径
        private string _Path;
        // 对象池节点
        private Transform _PoolNode;
        // 对象池
        private ObjectPool<GameObject> _Pool;
        // 资源加载器
        private ResLoader _resLoader;

        public GameObjectPool(Transform node, string path)
        {
            this._PoolNode = node;
            this._Path = path;
    
            this._Pool = new ObjectPool<GameObject>();
            this._resLoader = ResLoader.Alloc();
        }

        public void Dispose()
        {
            GameObject.Destroy(this._PoolNode.gameObject);
            if (_resLoader != null)
            {
                _resLoader.Recycle2Cache();
                _resLoader = null;
            }
        }
    
        /// <summary>
        /// 弹出对象
        /// </summary>
        /// <returns></returns>
        public void Pop(Action<GameObject> callback, bool autoActive)
        {
            if (this._Pool.Count > 0)
            {
                GameObject go = this._Pool.Pop();
                go.transform.SetParent(null);
                callback?.Invoke(go);
                if (autoActive && !go.activeSelf)
                {
                    go.SetActive(true);
                }
            }
            else
            {
                _resLoader.Add2Load(_Path, ((success, name, asset) =>
                {
                    if (success)
                    {
                        GameObject go = GameObject.Instantiate((UnityEngine.GameObject)asset, Vector3.zero, Quaternion.identity);
                        callback?.Invoke(go);
                        if (autoActive && !go.activeSelf)
                        {
                            go.SetActive(true);
                        }
                    }
                })).Load();
            }
            updatePoolNodeName();
        }
    
        /// <summary>
        /// 回收对象
        /// </summary>
        /// <param name="go"></param>
        public void Push(GameObject go)
        {
            go.transform.SetParent(this._PoolNode);
            go.SetActive(false);
            this._Pool.Push(go);
    
            updatePoolNodeName();
        }
    
        // 更新节点名称
        private void updatePoolNodeName()
        {
    #if UNITY_EDITOR && !ENABLE_PROFILER
            this._PoolNode.name = $"{this._Path} - {this._PoolNode.childCount}";
    #endif
        }
    
    }
    
}